package util

import com.github.thomasnield.rxkotlinfx.observeOnFx
import com.github.thomasnield.rxkotlinfx.onChangedObservable
import com.github.thomasnield.rxkotlinfx.toMaybe
import com.jfoenix.controls.*
import entity.MyContract
import entity.SysProperties
import io.reactivex.rxkotlin.toObservable
import javafx.geometry.Insets
import javafx.geometry.Orientation
import javafx.geometry.Pos
import javafx.scene.Node
import javafx.scene.control.ChoiceDialog
import javafx.scene.control.Label
import javafx.scene.control.TextInputDialog
import javafx.scene.input.KeyCode
import javafx.scene.layout.StackPane
import javafx.scene.paint.Color
import javafx.scene.text.Font
import javafx.scene.text.FontWeight
import javafx.stage.FileChooser
import javafx.stage.Window
import tornadofx.*
import view.MainWindow

object MyDialogs {

    fun chooseDocsFileDialog() = chooseFile(
            title = "选择文件导入",
            mode = FileChooserMode.Multi,
            filters = arrayOf(
                    FileChooser.ExtensionFilter("Doc", "*.doc"),
                    FileChooser.ExtensionFilter("Docx", "*.docx"),
                    FileChooser.ExtensionFilter("All File", "*.*")
            )
    )

    fun chooseDocFileDialog() = chooseFile(
            title = "选择文件导入",
            mode = FileChooserMode.Single,
            filters = arrayOf(
                    FileChooser.ExtensionFilter("Doc", "*.doc"),
                    FileChooser.ExtensionFilter("All File", "*.*")
            )
    )

    fun addDirDialog() = TextInputDialog("").apply {
        title = "添加目录"
        contentText = "目录名称"
        headerText = null
    }

    fun dataManagerDialog(father: Node, currentWindow: Window, sysProperties: SysProperties, mainWindow: MainWindow) {
        val dataControlList = JFXListView<Label>().apply {
            items.addAll(listOf(
                    Label("数据还原").apply {
                        minWidth = 100.0
                        maxHeight = 55.0
                        alignment = Pos.CENTER
                    },
                    Label("数据备份").apply {
                        minWidth = 100.0
                        maxHeight = 55.0
                        alignment = Pos.CENTER
                    }
            ))

            orientation = Orientation.HORIZONTAL
            minWidth = 250.0
            minHeight = 55.0
        }


        val popupDataControl = JFXPopup(dataControlList).apply {
            dataControlList.requestFocus()
        }
        popupDataControl.show(
                father,
                JFXPopup.PopupVPosition.TOP,
                JFXPopup.PopupHPosition.LEFT,
                currentWindow.width / 2 - 125,
                currentWindow.height / 2 - 70
        )

        dataControlList.selectionModel.selectedItems.onChangedObservable().switchMap { it.toObservable() }
                .observeOnFx()
                .subscribe {
                    when (it.text) {
                        "数据导入" -> {
                            val importFile =
                                    chooseFile(
                                            title = "选择数据包",
                                            mode = FileChooserMode.Single,
                                            filters = arrayOf(
                                                    FileChooser.ExtensionFilter("ZIP", "*.zip")
                                            )
                                    )
                            if (importFile.size == 1) {
                                mainWindow.mainPresenter.importDatas(importFile[0])
                            }
                            popupDataControl.hide()
                        }
                        "数据导出" -> {
                            val exportFile = chooseDirectory { title = "选择导出路径" }
                            if (exportFile != null) {
                                mainWindow.mainPresenter.exportDatas(exportFile.path)
                            }
                            popupDataControl.hide()
                        }
                    }
                    if (popupDataControl.isShowing) popupDataControl.hide()
                }

    }

    fun settingDialog(father: Node, currentWindow: Window, sysProperties: SysProperties, mainWindow: MainWindow) {
        val settingList = JFXListView<Label>().apply {
            items.addAll(listOf(
                    Label("账户修改").apply {
                        minWidth = 100.0
                        maxHeight = 55.0
                        alignment = Pos.CENTER
                    },
                    Label("主题设置").apply {
                        minWidth = 100.0
                        maxHeight = 55.0
                        alignment = Pos.CENTER
                    }
            ))

            orientation = Orientation.HORIZONTAL
            minWidth = 250.0
            minHeight = 55.0
        }


        val popupSetting = JFXPopup(settingList).apply {
            settingList.requestFocus()
        }
        popupSetting.show(
                father,
                JFXPopup.PopupVPosition.TOP,
                JFXPopup.PopupHPosition.LEFT,
                currentWindow.width / 2 - 125,
                currentWindow.height / 2 - 70
        )

        settingList.selectionModel.selectedItems.onChangedObservable().switchMap { it.toObservable() }
                .observeOnFx()
                .subscribe {
                    when (it.text) {
                        "账户修改" -> {

                            MyDialogs.showTextInputDialog(
                                    "密码确认",
                                    "旧密码:",
                                    "请输入旧密码！",
                                    father as StackPane
                            ) {
                                if (it.isNotEmpty() && MyEncodeUtil.encode(it) == sysProperties.loginPwd) {

                                    MyDialogs.showTwoLineTextInputDialog(
                                            "密码验证成功，请输入新用户名和密码",
                                            "用户名:",
                                            "密  码:",
                                            "请输入新用户名！",
                                            "请输入新的密码！",
                                            father
                                    ) {
                                        val newloginUser = it[0]
                                        val newloginPwd = it[1]

                                        if (newloginUser.isEmpty() || newloginPwd.isEmpty()) {
                                            MyDialogs.showAlertDialog("提示", "用户名和密码不能为空！", father)
                                            return@showTwoLineTextInputDialog
                                        }

                                        if (newloginUser == sysProperties.loginUser &&
                                                newloginPwd == sysProperties.loginPwd) {
                                            MyDialogs.showAlertDialog("提示", "新旧用户信息一致，修改未成功！", father)
                                        } else {
                                            sysProperties.loginUser = newloginUser
                                            sysProperties.loginPwd = MyEncodeUtil.encode(newloginPwd)

                                            mainWindow.saveSysProperties(sysProperties)

                                            MyDialogs.showAlertDialog("提示", "账户密码修改成功！", father)
                                        }
                                    }

                                } else {
                                    MyDialogs.showAlertDialog("提示", "密码错误，请重新操作！", father)
                                }
                            }
                        }
                        "主题设置" -> {
                            ChoiceDialog<String>(
                                    sysProperties.colorMode,
                                    mutableListOf(
                                            MyContract.NORMAL_COLOR_MODE,
//                                            MyContract.NIGHT_COLOR_MODE,
                                            MyContract.REAL_COLOR_MODE
                                    )
                            )
                                    .toMaybe()
                                    .toObservable()
                                    .filter { it.trim() != "" }
                                    .subscribe {
                                        sysProperties.colorMode = it
                                        mainWindow.saveSysProperties(sysProperties)
                                        mainWindow.changeWebPageColorMode(sysProperties.colorMode)
                                    }
                        }
                    }
                    if (popupSetting.isShowing) popupSetting.hide()
                }
    }

    fun modeChooseDialog(father: Node, currentWindow: Window, sysProperties: SysProperties, mainWindow: MainWindow) {
        val choiceMadeList = JFXListView<Label>().apply {
            items.addAll(listOf(
                    Label(MyContract.VIEW_MODE).apply {
                        minWidth = 100.0
                        maxHeight = 55.0
                        alignment = Pos.CENTER
                    },
                    Label(MyContract.NORMAL_MODE).apply {
                        minWidth = 100.0
                        maxHeight = 55.0
                        alignment = Pos.CENTER
                    }

            ))
            orientation = Orientation.HORIZONTAL
            minWidth = 250.0
            minHeight = 55.0
            selectionModel.select(Label(sysProperties.defaultMode))
        }

        val popupModelChoose = JFXPopup(choiceMadeList).apply {
            choiceMadeList.requestFocus()
        }
        popupModelChoose.show(
                father,
                JFXPopup.PopupVPosition.TOP,
                JFXPopup.PopupHPosition.LEFT,
                currentWindow.width / 2 - 125,
                currentWindow.height / 2 - 70
        )
        choiceMadeList.selectionModel.selectedItems.onChangedObservable().switchMap { it.toObservable() }
                .observeOnFx()
                .subscribe {
                    when (it.text) {
                        MyContract.VIEW_MODE -> {
                            mainWindow.toViewMode()
                        }
                        MyContract.NORMAL_MODE -> {
                            mainWindow.toNormalMode()
                        }
                        MyContract.EDIT_MODE -> {
                            mainWindow.toEditMode()
                        }
                    }
                    mainWindow.saveSysProperties(sysProperties)
                    if (popupModelChoose.isShowing) popupModelChoose.hide()
                }
    }

    fun showAlertDialog(title: String, msg: String, fatherStackPane: StackPane) {
        val alertDialog = JFXDialog()
        alertDialog.apply {
            content = anchorpane {
                padding = Insets(30.0)


                prefWidth = 300.0
                prefHeight = 200.0
                label(title).apply {
                    anchorpaneConstraints {
                        leftAnchor = 0.0
                        topAnchor = 0.0
                    }
                    font = Font.font("Black", FontWeight.BOLD, 30.0)
                }

                label(msg).apply {
                    isWrapText = true
                    anchorpaneConstraints {
                        leftAnchor = 0.0
                        topAnchor = 50.0
                    }
                    font = Font.font("Black", FontWeight.BOLD, 16.0)
                }
                this += JFXButton("确定").apply {
                    textFill= Color.BLUE
                    font = Font.font("Black", FontWeight.BOLD, 18.0)
                    anchorpaneConstraints {
                        rightAnchor = 0.0
                        bottomAnchor = 0.0
                    }

                    action {
                        alertDialog.close()
                    }
                }
            }
        }
        alertDialog.show(fatherStackPane)
    }

    fun showTextInputDialog(title: String, msg: String, promptStr: String, fatherStackPane: StackPane, op: (resultStr: String) -> Unit) {
        val alertDialog = JFXDialog()
        alertDialog.apply {
            content = anchorpane {
                padding = Insets(30.0)


                prefWidth = 300.0
                prefHeight = 200.0
                label(title).apply {
                    anchorpaneConstraints {
                        leftAnchor = 0.0
                        topAnchor = 0.0
                    }
                    font = Font.font("Black", FontWeight.BOLD, 30.0)
                }
                label(msg).apply {
                    maxWidth = 60.0
                    isWrapText = false
                    anchorpaneConstraints {
                        leftAnchor = 0.0
                        topAnchor = 60.0
                    }
                    font = Font.font("Black", FontWeight.BOLD, 16.0)
                }

                val inputTextField = JFXTextField().apply {
                    anchorpaneConstraints {
                        leftAnchor = 60.0
                        topAnchor = 50.0
                    }
                    promptText = promptStr
                    font = Font.font("Black", FontWeight.BOLD, 18.0)
                    requestFocus()
                }
                inputTextField.setOnKeyPressed {
                    if (it.code == KeyCode.ENTER) {
                        op(inputTextField.text.trim())
                        alertDialog.close()
                    }

                }

                this += inputTextField

                this += JFXButton("确定").apply {
                    textFill= Color.BLUE
                    font = Font.font("Black", FontWeight.BOLD, 18.0)
                    anchorpaneConstraints {
                        rightAnchor = 0.0
                        bottomAnchor = 0.0
                    }

                    action {
                        op(inputTextField.text.trim())
                        alertDialog.close()
                    }
                }
            }
        }
        alertDialog.show(fatherStackPane)
    }

    fun showTwoLineTextInputDialog(title: String, msg1: String, msg2: String, promptStr1: String, promptStr2: String, fatherStackPane: StackPane, op: (resultArray: Array<String>) -> Unit) {
        val alertDialog = JFXDialog()
        alertDialog.apply {
            content = anchorpane {
                padding = Insets(30.0)


                prefWidth = 350.0
                prefHeight = 260.0
                label(title).apply {
                    anchorpaneConstraints {
                        leftAnchor = 0.0
                        topAnchor = 0.0
                    }
                    font = Font.font("Black", FontWeight.BOLD, 24.0)
                }
                label(msg1).apply {
                    maxWidth = 60.0
                    isWrapText = false
                    anchorpaneConstraints {
                        leftAnchor = 80.0
                        topAnchor = 60.0
                    }
                    font = Font.font("Black", FontWeight.BOLD, 16.0)
                }

                val inputTextField1 = JFXTextField().apply {
                    anchorpaneConstraints {
                        leftAnchor = 140.0
                        topAnchor = 50.0
                    }
                    promptText = promptStr1
                    font = Font.font("Black", FontWeight.BOLD, 16.0)
                    requestFocus()
                }
                val inputTextField2 = JFXTextField().apply {
                    anchorpaneConstraints {
                        leftAnchor = 140.0
                        topAnchor = 90.0
                    }
                    promptText = promptStr2
                    font = Font.font("Black", FontWeight.BOLD, 16.0)
                }

                inputTextField1.setOnKeyPressed {
                    if (it.code == KeyCode.ENTER) {
                        inputTextField2.requestFocus()
                    }
                }
                inputTextField2.setOnKeyPressed {
                    if (it.code == KeyCode.ENTER) {
                        op(arrayOf(inputTextField1.text.trim(), inputTextField2.text.trim()))
                        alertDialog.close()
                    }
                }


                this += inputTextField1


                label(msg2).apply {
                    maxWidth = 60.0
                    isWrapText = false
                    anchorpaneConstraints {
                        leftAnchor = 80.0
                        topAnchor = 100.0
                    }
                    font = Font.font("Black", FontWeight.BOLD, 16.0)
                }


                this += inputTextField2




                this += JFXButton("确定").apply {
                    textFill= Color.BLUE
                    font = Font.font("Black", FontWeight.BOLD, 18.0)
                    anchorpaneConstraints {
                        rightAnchor = 0.0
                        bottomAnchor = 0.0
                    }

                    action {
                        op(arrayOf(inputTextField1.text.trim(), inputTextField2.text.trim()))
                        alertDialog.close()
                    }
                }
            }
        }
        alertDialog.show(fatherStackPane)
    }
}